<script setup>
// 集成所有组件
import C from "@/components/C";
import { onMounted, getCurrentInstance, nextTick, computed } from "vue";
// import { useTogglePopup } from "@/hooks/app-hook";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import socket from "./socket";
import Indexdb from "@/utils/indexdb";
import clone from "@/utils/clone"

const db = new Indexdb("qq");
const store = useStore();
const user = store.state.user;
const notify = store.state.notify;
const instance = getCurrentInstance();
const app = instance.appContext.app;
const token = computed(() => user.token);
const userInfo = computed(() => user.userInfo);
const route = useRoute();


let nowChats = computed(() => {
  return notify.nowChats;
});

onMounted(() => {
  // 消息ArrayBuffer存到Vuex中并做持久化到 Indexdb 中
  // 读取时针对 ArrayBuffer 进行 Blob Url 的生成 不能直接存 Blob Url
  socket.on(user.userInfo._id, (message) => {
console.log(route.path);
    let u = message.fromUser;
    if (message.isImg) {
      app.$bus.emit("setImgsList", message.msg);
    }
    let chatInfo = {
      id: u._id,
      id2: user.userInfo._id,
      avatar:
        "http://q4.qlogo.cn/headimg_dl?dst_uin=" + u.qq_account + "&spec=100",
      title: u.nick_name,
      type: u.type,
      messages: [
        {
          from: "other",
          date: Date.now(),
          msg: message.msg,
          readStatus: route.path === "/chat" ? true : false,
          qq: u.qq_account,
          isEmjoi: u.isEmjoi,
          alt: message.isImg
            ? "[图片]"
            : message.isVideo
            ? "[视频]"
            : message.isAudio
            ? "[语音]"
            : u.alt,
          isImg: message.isImg ? true : false,
          blobSrc: message.msg,
          isVideo: message.isVideo ? message.isVideo : false,
          isAudio: message.isAudio ? message.isAudio : false,
          voiceDuration: message.voiceDuration,
        },
      ],
    };
    let findChatUIndex = nowChats.value.findIndex((v, i) => v.id === u._id);
    if (findChatUIndex >= 0) {
      nowChats.value[findChatUIndex]["messages"].push({
        from: "other",
        date: Date.now(),
        msg: message.msg,
        readStatus: route.path === "/chat" ? true : false,
        qq: u.qq_account,
        isEmjoi: u.isEmjoi,
        alt: message.isImg
          ? "[图片]"
          : message.isVideo
          ? "[视频]"
          : message.isAudio
          ? "[语音]"
          : u.alt,
        isImg: message.isImg ? true : false,
        isVideo: message.isVideo ? message.isVideo : false,
        blobSrc: message.msg,
        isAudio: message.isAudio ? message.isAudio : false,
        voiceDuration: message.voiceDuration,
      });
    } else {
      nowChats.value.push(chatInfo);
    }
    // console.log(nowChats);
    store.dispatch("notify/setNowChats", nowChats.value);
    (async () => {
      console.log(666);
      const noProxy = clone(notify.nowChats);
      const lines = await db.selectAll("chat_record");
      if (lines.length >= 1) {
        db.put("chat_record", {
          id: lines[0]["id"],
          nowChats: noProxy,
        }).then((r) => {
          // console.log(r);
        });
      } else {
        db.add("chat_record", {
          nowChats: noProxy,
        })
          .then((success) => {})
          .catch((err) => {});
      }
    })();
    nextTick(() => {
      const mainBox = document.getElementById("main");
      mainBox.scrollTop = main.offsetHeight + main.scrollHeight;
    });
    // app.$bus.emit("reciveMessage", 1);
  });
});

app.$bus.on("reciveMessage", (notifyCount) => {
  store.dispatch("notify/setAddNotifyCount", 1);
});

const handlerNavBarTop = (e) => {
  if (e.target.scrollTop > 330) {
    app.$bus.emit("changeNavBarTopBgColor", "#08f");
  } else {
    app.$bus.emit("changeNavBarTopBgColor", "transparent");
  }
};
</script>

<template>
  <C.Popup />
  <!-- 侧边导航栏 -->
  <div class="container">
    <!-- 顶部导航栏 -->
    <C.Header />
    <!-- 路由视图区域 -->
    <router-view
      class="main"
      id="main"
      ref="main"
      @scroll="handlerNavBarTop"
      v-slot="{ Component }"
    >
      <transition-group name="fade">
        <component :is="Component" :key="Component" />
      </transition-group>
    </router-view>
    <!-- 底部菜单区域 -->
    <C.Footer v-if="token !== '' && JSON.stringify(userInfo) !== '{}'" />
  </div>
</template>

<style lang="scss">
:root {
  --van-nav-bar-icon-color: #999;
  --van-nav-bar-height: 50px;
  --van-active-opacity: 1;
  --van-badge-size: 20px;
}

.van-badge--bottom-right {
  bottom: 25px;
  right: 35px;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  .header {
    height: 50px;
  }
  .footer {
    height: 50px;
  }
  .main {
    flex: 1;
    overflow-y: scroll;
  }
  .van-cell__title {
    padding-left: 5px !important;
  }
}

.fade-enter-active {
  animation: animate 0.5s;
}
@keyframes animate {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
